// gjw/pages/store/register.js
const app = getApp()
var imgArray=[]
Page({

  /**
   * 页面的初始数据
   */
  data: {
    fenlei: ['玉器', '竹木', '石刻',],
    objectArray: [
      {
        id: 0,
        name: '玉器'
      },
      {
        id: 1,
        name: '竹木'
      },
      {
        id: 2,
        name: '石刻'
      },
    ],
    type: ['普通商家', '定制商家'],
    objectArray: [
      {
        id: 0,
        name: '普通商家'
      },
      {
        id: 1,
        name: '定制商家'
      },
    ],
    multiIndex: [0, 0, 0],
    region: ['', '', ''],
    tishi:false,
    diqu:true,
    storeImg: '../images/tu.png',
    txImg:'../images/tu.png',
    // cardImg: [],
    message: '获取验证码',
    currentTime: 60,
    yan: 'get_code',
    tuijian: [
      { name: 1, value: '推荐' },
      { name: 0, value: '不推荐' },
    ],
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that=this
    app.location_attachurl(this)
    app.location_url(this)
    that.logo()    
    that.identy()
    that.getlx()
    that.payNum()
    var siteUrl = wx.getStorageSync('siteUrl')
    that.setData({
      siteUrl: siteUrl
    })

  },
  
  logo: function (e) {
    var that = this
    app.util.request({
      url: 'entry/wxapp/logo',
      success: function (res) {
        
        that.setData({
          logo: res.data.res
        })
      }
    })
  },
  // 判断身份
  identy: function (e) {
    var that = this
    var openid = wx.getStorageSync('openid')
    
    app.util.request({
      url: 'entry/wxapp/Iscustomers',
      data: { openid: openid },
      success: function (res) {
        
        if (res.data.code == 200 || res.data.code == 204){
          // 认证审核通过
          wx.redirectTo({
            url: '../store/data',
          })
        }else if (res.data.code == 201) {    //商家审核未通过  用户
         wx.showModal({
           title: '提示',
           content: '你的认证资料正在审核中，请耐心等待...',
           showCancel:false,
           success:function(res){
             if(res.confirm){
               wx.navigateBack({
                 delta: 1,
               })
             }
           }
         })
        }else if(res.data.code==202){
          wx.showModal({
            title: '提示',
            content: '您的资料审核未通过,是否重新认证？',
            success: function (res) {
              if (res.confirm) {
                
                
              } else if (res.cancel) {
                
                wx.navigateBack({
                  delta: 1,
                })
              }
            }
          })
        }
      }
    })
  },

  // 获取类型
  getlx: function (e) {
    var that=this
    app.util.request({
      url: 'entry/wxapp/catestop',
      success: function (res) {
        
        var fenlei=[]
        var arr=res.data.res
        for(var i=0;i<arr.length;i++){
          fenlei.push(arr[i].cate)
        }
        that.setData({
          fl: arr,
          fenlei:fenlei
        })
      }
    })
  },


  bindPickerChange: function (e) {
    
    this.setData({
      index: e.detail.value
    })
  },

  bindPickerType: function (e) {
    
    this.setData({
      t_index: e.detail.value
    })
    
  },

  bindRegionChange: function (e) {
    
    var show = false
    var hide = true
    this.setData({
      tishi: hide,
      diqu: show,
      region: e.detail.value,
      address: e.detail.value[0] + e.detail.value[1] + e.detail.value[2] 
    })
  },

  change: function (e) {
    
    this.setData({
      phone: e.detail.value
    })

  },


  //倒计时
  getCode: function (e) {
    var that = this;
    var yes = true
    var no = false
    //输入的手机号
    var currentNum = that.data.phone;
    var currentTime = that.data.currentTime;
    var interval = setInterval(function () {
      currentTime--;
      that.setData({
        message: '剩' + currentTime + '秒',
        disabled: yes,
      })
      if (currentTime <= 0) {
        clearInterval(interval)
        that.setData({
          message: "重新获取",
          currentTime: 60,
          disabled: no,
          yan: 'get_code',
        })
      }
    }, 1000)
  },

  get_code: function (e) {
    var that = this;
    // console.log(that)
    var compphone = that.data.phone;
    var myreg = /^0{0,1}(13[0-9]|15[0-9]|18[0-9]|17[0-9])[0-9]{8}$/;

    if (!myreg.test(compphone)) {
      wx.showToast({
        title: '您输入的手机号有误!',
        icon: "none",
      })
    } else {
      that.setData({
        yan: 'on_yan'
      })
      that.getCode();
      // // 获取6位数的随机数
      var recive_code = "";
      for (var i = 0; i < 6; i++) {
        recive_code += Math.floor(Math.random() * 10);
      }
      that.setData({
        disabled: true,
        recive_code: recive_code
      })
      // 随机数传给后台
      app.util.request({
        'url': 'entry/wxapp/Code',
        'cachetime': '0',
        data: {
          code: recive_code,
          phone: compphone
        },
        success: function (res) {
          

        }
      })
    }
  },

  getImg: function (e) {
    var that = this
    var siteUrl = wx.getStorageSync('siteUrl')
    
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths
        

        wx.uploadFile({
          url: wx.getStorageSync('siteUrl') + 'app/index.php?i=' + wx.getStorageSync('uniacid') + '&c=entry&a=wxapp&do=Uploads&m=zh_gjw', //仅为示例，非真实的接口地址
          filePath: tempFilePaths[0],
          name: 'upload_file',
          formData: {
            'user': 'test'
          },
          success: function (res) {
            var data = res.data
            
            that.setData({
              strImg: data,   //提交字符串
              storeImg: siteUrl + 'attachment/' + data    //显示
            })
          }
        })


      }
    })
  },

  photoImg: function (e) {
    var that = this
    var siteUrl = wx.getStorageSync('siteUrl')
    
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths
        

        wx.uploadFile({
          url: wx.getStorageSync('siteUrl') + 'app/index.php?i=' + wx.getStorageSync('uniacid') + '&c=entry&a=wxapp&do=Uploads&m=zh_gjw', //仅为示例，非真实的接口地址
          filePath: tempFilePaths[0],
          name: 'upload_file',
          formData: {
            'user': 'test'
          },
          success: function (res) {
            var data = res.data
            
            that.setData({
              stxImg: data,   //提交字符串
              txImg: siteUrl + 'attachment/' + data    //显示
            })
          }
        })


      }
    })
  },


  arrImg: function (e) {
    var that = this
    var siteUrl = wx.getStorageSync('siteUrl')
    var str
    // console.log(cardImg)
    var img_length = 2 - imgArray.length
    
    if (img_length > 0 && img_length <3) {
      wx.chooseImage({
        count: 2, // 默认9
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function (res) {
          // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          var tempFilePaths = res.tempFilePaths
          
          // imgArray = imgArray.concat(tempFilePaths)
          // console.log(cardImg)
          // str = cardImg.join(",")
          // console.log(str)
          that.upload({
            url: wx.getStorageSync('siteUrl') + 'app/index.php?i=' + wx.getStorageSync('uniacid') + '&c=entry&a=wxapp&do=Uploads&m=zh_gjw',
            path: tempFilePaths
          });
        }
      })
    }
     
  },

  delete_img: function (e) {
    var that=this
    var index = e.currentTarget.dataset.index
    imgArray=imgArray.splice(index, 1)
    
    that.setData({
      imgArray: imgArray
    })
  },

  // upload:function(e){
  //   var that=this
  //   wx.uploadFile({
  //     url: wx.getStorageSync('siteUrl') + 'app/index.php?i=' + wx.getStorageSync('uniacid') + '&c=entry&a=wxapp&do=Uploads&m=zh_gjw', //仅为示例，非真实的接口地址
  //     filePath: str,
  //     name: 'upload_file',
  //     formData: {
  //       'user': 'test'
  //     },
  //     success: function (res) {
  //       var data = res.data
  //       
  //       that.setData({
  //         strImg: data,   //提交字符串
  //         cardImg: cardImg    //显示
  //       })
  //     }
  //   })
  // },
  upload: function (data) {
    var that = this,
      i = data.i ? data.i : 0,
      success = data.success ? data.success : 0,
      fail = data.fail ? data.fail : 0;
    wx.uploadFile({
      url: data.url,
      filePath: data.path[i],
      name: 'upload_file',
      formData: null,
      success: (resp) => {
        if (resp.data != '') {
          success++;
          imgArray.push(resp.data)
          that.setData({
            imgArray:imgArray
          })
          
        }
        else {
          wx.showToast({
            icon: "loading",
            title: "请重试"
          })
        }
      },
      fail: (res) => {
        fail++;
      },
      complete: () => {
        
        i++;
        if (i == data.path.length) {
          that.setData({
            images: data.path
          });
          wx.hideToast();
        } else {
          
          data.i = i;
          data.success = success;
          data.fail = fail;
          that.upload(data);
        }

      }
    });
  },

  payNum:function(e){
   var that=this
   app.util.request({
     url:'entry/wxapp/Cusmoney',
      success:function(res){
        
        that.setData({
          pay:res.data.res.publishfee,
          dpay: res.data.res.dpublishfee
        })
      }
   })
  },


  sub: function (e) {
    var that=this
    
    var formid = e.detail.formId
		var openid = wx.getStorageSync('openid')
    var t_index = that.data.t_index
    var i = that.data.index 
    var reg = /^0{0,1}(13[0-9]|15[0-9]|18[0-9]|17[0-9])[0-9]{8}$/
    var mima = /^(?![A-Z]+$)(?![a-z]+$)(?!\d+$)\S{6,}$/
    var arry = e.detail.value
    var storeName = arry.storeName
    var storeType = arry.type
    var storeArea = arry.storeArea[0] + arry.storeArea[1] + arry.storeArea[2]
    var storeInfo = arry.storeInfo
    var trueName = arry.trueName
    var phone = arry.phone
    var code = arry.code
    var password = arry.password
    var n_code = that.data.recive_code
    var stxImg = that.data.stxImg
    var storeImg = that.data.strImg
    var imgArray = that.data.imgArray
  
    if (t_index == undefined) {
      wx.showToast({
        title: '请选择商家类型',
        icon: 'none',
      })
    } else if(i==undefined){
      wx.showToast({
        title: '请选择经营类型',
        icon:'none',
      })
    } else if (storeName==''){
      wx.showToast({
        title: '请输入商家名称',
        icon: 'none',
      })
    } else if (storeArea == '') {
      wx.showToast({
        title: '请选择商家地址',
        icon: 'none',
      })
    } else if (storeInfo == '') {
      wx.showToast({
        title: '请填写详细地址',
        icon: 'none',
      })
    } else if (trueName == '') {
      wx.showToast({
        title: '请填写真实姓名',
        icon: 'none',
      })
    } else if (phone=='') {
      wx.showToast({
        title: '手机号码不能为空',
        icon: 'none',
      })
    } else if (!(reg.test(phone))) {
      wx.showToast({
        title: '手机号码格式不正确',
        icon: 'none',
      })
    } else if (code == '') {
      wx.showToast({
        title: '请输入验证码',
        icon: 'none',
      })
    } else if (code!=n_code) {
      wx.showToast({
        title: '验证码有误',
        icon: 'none',
      })
   } else if (password=='') {
     wx.showToast({
       title: '请设置后台密码',
       icon: 'none',
     })
   } else if (!(mima.test(password))) {
      wx.showToast({
        title: '后台密码须是字母和数字',
        icon: 'none',
      })
    } else if (stxImg == undefined) {
      wx.showToast({
        title: '请上传头像展示图片',
        icon: 'none',
      })
    }
		//  else if (storeImg == undefined) {
    //   wx.showToast({
    //     title: '请上传营业执照图片',
    //     icon: 'none',
    //   })
    // }
		 else if (imgArray == undefined) {
     wx.showToast({
       title: '请上传2张身份证照片',
       icon: 'none',
     })
    }else if (t_index == 0) {   //普通商家
      var fenlei = that.data.fl
      var c_id = fenlei[i].id
      var c_name = fenlei[i].cate
      var cardImg = that.data.imgArray.join(',')
      
      var publishfee = Number(that.data.pay)
      
      wx.showModal({
        title: '提示',
        content: '你选择的商家类型为普通商家，提交之后无法修改',
        success: function (res) {
          if (res.confirm) {
            app.util.request({
              url: 'entry/wxapp/cusmanage',
              data: {
								openid: openid, formid: formid, avatar: wx.getStorageSync('avatarUrl'), shotcate: c_name, shot_id: c_id, cusname: storeName, cusaddress: storeArea, addressdetail: storeInfo, username: trueName, phone: phone, storeimg: stxImg, liceneimg: storeImg, cardimg: cardImg, password: password, type: storeType,
              },
              success: function (res) {
                
                that.setData({
                  res_id: res.data.res_id
                })
                var res_id = that.data.res_id
                if (res.data.code == 203 || res.data.code == 200){
                    if(publishfee==0){
                      app.util.request({
                        url: 'entry/wxapp/Cuspaysuccess',
                        data: {
                          res_id: res_id
                        },
                        success: function (res) {
                          
                          
                           if (res.data.code == 200) {
                            wx.showModal({
                              title: '提示',
                              content: '您的资料已经成功提交，请耐心等待审核',
                              success: function (res) {
                                if (res.confirm) {
                                  
                                  wx.reLaunch({
                                    url: '../index/index',
                                  })
                                }
                              }
                            })
                          }
                        }
                      })
                    }else{
                      
                      
                      
                      app.util.request({
                      url: 'entry/wxapp/Cuspay',
                      data: {
                        openid: openid, publishfee: publishfee, res_id: res_id
                      },
                      success: function (res) {
                        
                        wx.requestPayment({
                          'timeStamp': res.data.timeStamp,
                          'nonceStr': res.data.nonceStr,
                          'package': res.data.package,
                          'signType': 'MD5',
                          'paySign': res.data.paySign,
                          'success': function (res) {
                            app.util.request({
                              url: 'entry/wxapp/Cuspaysuccess',
                              data: {
                                res_id: res_id
                              },
                              success: function (res) {
                                
                                
                                if (res.data.code == 200) {
                                  wx.showModal({
                                    title: '提示',
                                    content: '您的资料已经成功提交，请耐心等待审核',
                                    success: function (res) {
                                      if (res.confirm) {
                                        
                                        wx.reLaunch({
                                          url: '../index/index',
                                        })
                                      }
                                    }
                                  })
                                }
                              }
                            })

                          },
                          'fail': function (res) {
                            
                            wx.showToast({
                              title: '支付失败',
                              icon: "loading",
                            })
                          },
                          'complete': function (res) {
                            
                            wx.showToast({
                              title: '取消支付',
                              icon: "loading",
                            })
                          }
                        })
                      }

                      })
                    }
                }else if(res.data.code==203){  //认证成功
                  wx.showModal({
                    title: '提示',
                    content: '恭喜您已认证通过',
                    showCancel: 'false',
                    success: function (res) {
                      if (res.confirm) {
                        
                        wx.navigateTo({
                          url: '../store/data',
                        })
                      }
                    }
                  })
                }
              }
            })
          }
        }
      })
    } else if (t_index == 1) {     //定制商家
      var fenlei = that.data.fl
      var c_id = fenlei[i].id
      var c_name = fenlei[i].cate
      var cardImg = that.data.imgArray.join(',')      
      var publishfee = Number(that.data.dpay)
      wx.showModal({
        title: '提示',
        content: '你选择的商家类型为定制商家，须有定制资格，提交之后无法修改',
        success: function (res) {
          if (res.confirm) {
            app.util.request({
              url: 'entry/wxapp/cusmanage',
              data: {
                openid: openid, formid: formid, shotcate: c_name, shot_id: c_id, cusname: storeName, cusaddress: storeArea, addressdetail: storeInfo, username: trueName, phone: phone, storeimg: stxImg, liceneimg: storeImg, cardimg: cardImg, password: password, type: storeType,
              },
              success: function (res) {
                
                that.setData({
                  res_id: res.data.res_id
                })
                var res_id = that.data.res_id
                if (res.data.code == 203 || res.data.code == 200){
                  if(publishfee==0){
                    app.util.request({
                      url: 'entry/wxapp/Cuspaysuccess',
                      data: {
                        res_id: res_id
                      },
                      success: function (res) {
                        
                        
                        if (res.data.code == 200) {
                          wx.showModal({
                            title: '提示',
                            content: '您的资料已经成功提交，请耐心等待审核',
                            showCancel: false,
                            success: function (res) {
                              if (res.confirm) {
                                
                                wx.reLaunch({
                                  url: '../index/index',
                                })
                              }
                            }
                          })
                        }
                      }
                    })
                  }else{
                    app.util.request({
                      url: 'entry/wxapp/Cuspay',
                      data: {
                        openid: openid, publishfee: publishfee, res_id: res_id
                      },
                      success: function (res) {
                        
                        wx.requestPayment({
                          'timeStamp': res.data.timeStamp,
                          'nonceStr': res.data.nonceStr,
                          'package': res.data.package,
                          'signType': 'MD5',
                          'paySign': res.data.paySign,
                          'success': function (res) {
                            app.util.request({
                              url: 'entry/wxapp/Cuspaysuccess',
                              data: {
                                res_id: res_id
                              },
                              success: function (res) {
                                
                                
                                if (res.data.code == 200) {
                                  wx.showModal({
                                    title: '提示',
                                    content: '您的资料已经成功提交，请耐心等待审核',
                                    success: function (res) {
                                      if (res.confirm) {
                                        
                                        wx.reLaunch({
                                          url: '../index/index',
                                        })
                                      }
                                    }
                                  })
                                }
                              }
                            })

                          },
                          'fail': function (res) {
                            
                            wx.showToast({
                              title: '支付失败',
                              icon: "loading",
                            })
                          },
                          'complete': function (res) {
                            
                            wx.showToast({
                              title: '取消支付',
                              icon: "loading",
                            })
                          }
                        })
                      }

                    })
                  }
                }else if(res.data.code==203){
                  wx.showModal({
                    title: '提示',
                    content: '恭喜您已认证通过',
                    showCancel: 'false',
                    success: function (res) {
                      if (res.confirm) {
                        
                        wx.navigateTo({
                          url: '../store/data',
                        })
                      }
                    }
                  })
                }
              }
            })
          }
        }
      })
    } 
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})